package com.leesche.zcsp.node.web.controller.web.v2.usermanage.factory;

import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddUserInfoCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import com.leesche.zcsp.node.web.vo.v2.FactoryUserVo;
import com.leesche.zcsp.node.web.vo.v2.Menu;
import com.leesche.zcsp.node.web.vo.v2.RoleVo;
import com.leesche.zcsp.node.web.vo.v2.UserBusinessInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/12/7 14:52: * 创建该类并实现业务逻辑: *********
 * @Title: WebIndividualController.java
 * @Description: TODO( “我的”Controller类)
 * @date 2016/12/7 14:52
 */
@Controller
@RequestMapping("/v2/factory/individual")
public class WebFactoryUserManageController {

    private static final Logger logger = Logger.getLogger(WebFactoryUserManageController.class);

    @Autowired
    private PrivilegeService privilegeService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserBusinessInfoService sysUserBusinessInfoService;

    @Autowired
    private SysModuleService sysModuleService;

    @Autowired
    private SysRoleModuleService sysRoleModuleService;

    private static final String FACTORY_USERS_RATEMANAGEMET = "web/v2/individual/factory/users_ratemanagement";
    private static final String FACTORY_USERS_SYSTEMUSER = "web/v2/individual/factory/users_systemuser";
    private static final String FACTORY_USERS_BUSINSSUSER = "web/v2/individual/factory/users_businssuser";
    private static final String FACTORY_USERS_SYSTEMUSER_ADDROLE = "web/v2/individual/factory/users_addsystemrole";

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示增加系统用户角色界面)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/businssuser", method = RequestMethod.GET)
    public String showBusinssView(Model model) {
        return FACTORY_USERS_BUSINSSUSER;
    }

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示用户的费率信息)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/ratemanage", method = RequestMethod.GET)
    public String showRateManageView(Model model) {

        QuerySysUserBusinessInfoCondition condition = new QuerySysUserBusinessInfoCondition();
        condition.setParentid(privilegeService.getCurrentPrincipal().getUserid());
        List<SysUserBusinessInfoDto> sysUserBusinessInfoDtos = sysUserBusinessInfoService.findListsByCondition(condition);
        if (sysUserBusinessInfoDtos != null && sysUserBusinessInfoDtos.size() > 0) {

            List<UserBusinessInfo> UserBusinessInfos = new ArrayList<UserBusinessInfo>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (SysUserBusinessInfoDto dto : sysUserBusinessInfoDtos) {
                UserBusinessInfo ub = new UserBusinessInfo();
                ub.setId(dto.getBusinessinfoid());
                ub.setUserno(dto.getBusinessno());
                ub.setBusinessNumber(dto.getMerchantnumber());
                ub.setRate(dto.getRate());
                ub.setUserMobile(dto.getMobile());
                ub.setUserName(dto.getUsername());
                ub.setCreateTime(dateFormat.format(dto.getUpdatetime()));
                UserBusinessInfos.add(ub);
            }
            model.addAttribute("userbusiness", UserBusinessInfos);
        }

        return FACTORY_USERS_RATEMANAGEMET;
    }

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示用户的费率信息)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/systemuser", method = RequestMethod.GET)
    public String showSystemUserView(Model model) {
        QuerySysRoleCondition condition = new QuerySysRoleCondition();
        condition.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
        condition.setNtype(3);//工厂系统角色
        List<SysRoleDto> dtos = sysRoleService.findListsByCondition(condition);
        List<RoleVo> roles = null;
        if (dtos != null || dtos.size() > 0) {
            roles = new ArrayList<RoleVo>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (SysRoleDto dto : dtos) {
                RoleVo role = new RoleVo();
                role.setId(dto.getRoleid());
                role.setParentid(dto.getProleid());
                role.setName(dto.getNamecn());
                role.setType(dto.getNtype());
                role.setCreateTime(dateFormat.format(dto.getUpdatetime()));
                roles.add(role);
            }
        }
        model.addAttribute("systemroles", roles);
        return FACTORY_USERS_SYSTEMUSER;
    }

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示增加系统用户角色界面)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/addsystemrole", method = RequestMethod.GET)
    public String showSystemUserRoleView(Model model) {
        Principal principal = privilegeService.getCurrentPrincipal();
        QuerySysRoleModuleCondition condition = new QuerySysRoleModuleCondition();
        condition.setAdminid(principal.getUserid());
        condition.setNtype(principal.getNtype());
        condition.setIsshare(1);
        condition.setIsdefault(1);
        condition.setState(1);
        List<Menu> menus = sysModuleService.findAllSysModuleTrees(condition);
        model.addAttribute("modules", menus);
        return FACTORY_USERS_SYSTEMUSER_ADDROLE;
    }

    /**
     * @Title: getRoles
     * @Description: TODO(新增用户子角色)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "addsystemrole", method = RequestMethod.POST)
    public Map<String, Object> addSystemUserRoleView(String rolename, Integer roleType, Long[] modules) {
        try {

            if (rolename == null || "".equals(rolename)) {
                return WebResult.failure("角色名称不能为空").toMap();
            } else if (roleType == null) {
                //roleType ： 3 工厂子用户
                return WebResult.failure("用户类型不能为空").toMap();
            }

            Long userid = privilegeService.getCurrentPrincipal().getUserid();
            QuerySysUserRoleCondition condition = new QuerySysUserRoleCondition();
            condition.setUserid(userid);
            SysUserRoleDto dto = sysUserRoleService.findByCondition(condition);

            if (dto != null) {
                SysRole role = new SysRole();
                role.setProleid(dto.getRoleid());
                role.setAdminid(userid);
                role.setNamecn(rolename);
                role.setSname("user define");
                role.setNtype(roleType); //3.工厂系统角色
                role.setUpdatetime(new Date());
                role.setState(1);
                role.setIsdefault(1);
                role.setIsshare(1);
                role.setRemark("自定义子角色");

                if (sysRoleService.insertSelective(role) > 0) {

                    if(modules != null && modules.length > 0){
                        List<SysRoleModule> sysRoleModules = new ArrayList<SysRoleModule>();
                        Date updatetime = new Date();
                        for (Long module : modules) {
                            SysRoleModule rm = new SysRoleModule();
                            rm.setRoleid(role.getRoleid());
                            rm.setModuleid(module);
                            rm.setAdminid(userid);
                            rm.setUpdatetime(updatetime);
                            sysRoleModules.add(rm);
                        }
                        sysRoleModuleService.setupRoleModule(sysRoleModules);
                    }

                    return WebResult.success().toMap();
                } else
                    return WebResult.failure("新增角色失败,请稍后重试").toMap();
            } else {
                return WebResult.failure("您尚未分配角色，请与管理员联系").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: changeUserRate(Long userbusinssid, Float rate)
     * @Description: TODO(更换用户的费率)
     * @author Jerry Chan
     * @date 2016/12/15 21:25
     */
    @ResponseBody
    @RequestMapping(value = "editrate", method = RequestMethod.POST)
    public Map<String, Object> changeUserRate(Long userbusinssid, Float rate) {
        try {

            if (userbusinssid == null || userbusinssid == 0) {
                return WebResult.failure("请选择需要编辑费率的用户").toMap();
            } else if (rate == null) {
                return WebResult.failure("请输入用户的费率").toMap();
            } else {
                SysUserBusinessInfo info = new SysUserBusinessInfo();
                info.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
                info.setUpdatetime(new Date());
                info.setBusinessinfoid(userbusinssid);
                info.setRate(rate);
                if (sysUserBusinessInfoService.updateByPrimaryKeySelective(info) > 0)
                    return WebResult.success().toMap();
                else
                    return WebResult.failure("编辑用户费率失败，请与管理员联系").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showUserBalanceDetailTotalRecord()
     * @Description: TODO(获取角色下的系统用户信息)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "getsystemuser", method = RequestMethod.GET)
    public Map<String, Object> getsystemuserinfo(final Long roleid) {
        try {

            if (roleid == null) {
                return WebResult.failure("没有选择具体的角色，请选择").toMap();
            }

            QuerySysUserRoleCondition condition = new QuerySysUserRoleCondition();
            condition.setUserid(privilegeService.getCurrentPrincipal().getUserid());
            condition.setRoleid(roleid);
            List<SysUserRoleDto> dtos = sysUserRoleService.findListsByCondition(condition);
            if (dtos != null && dtos.size() > 0) {
                List<FactoryUserVo> userInfos = new ArrayList<FactoryUserVo>();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (SysUserRoleDto dto : dtos) {
                    FactoryUserVo user = new FactoryUserVo();
                    user.setUserid(dto.getUserid());
                    user.setUsername(dto.getUsername());
                    user.setRegTime(format.format(dto.getCreatetime()));
                    userInfos.add(user);
                }
                return WebResult.success().put("userinfos", userInfos).toMap();
            }
            return WebResult.failure("该角色下，尚未有用户使用").toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: addChildUser(AddUserInfoCommand childUser)
     * @Description: TODO(工厂用户新增工厂系统用户)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "addsystemuser", method = RequestMethod.POST)
    public Map<String, Object> addSystemUser(AddUserInfoCommand childUser) {
        try {

            SysUser newUser = new SysUser();
            newUser.setUsername(childUser.getUsername());
            if (sysUserService.findUserByUsername(newUser) != null) {
                return WebResult.failure("'" + childUser.getUsername() + "'用户名已经存在，请使用其他用户名").toMap();
            }

            Principal parentUser = privilegeService.getCurrentPrincipal();

            Long parentUserID = parentUser.getUserid();

            QuerySysUserCondition condition = new QuerySysUserCondition();
            condition.setNtype(childUser.getNtype());
            condition.setParentid(parentUserID);
            condition.setGetBusinssNo(true);
            SysUserDto userDto = sysUserService.findByCondition(condition);
            //SysUser lastChildUser = sysUserService.findLastUserByParentID(parentUserID);
            String newChildBusinessno = null;
            if (userDto != null) {
                newChildBusinessno = String.valueOf(Long.parseLong(userDto.getBusinessno()) + 1);
            } else {
                newChildBusinessno = parentUser.getBusinessno() + "01";
            }

            newUser.setNtype(3);//3表示工厂系统用户
            newUser.setBusinessno(newChildBusinessno);
            newUser.setAdminid(parentUserID);
            newUser.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR,
                    childUser.getTimeDifference() <= 0 ? 3
                            : childUser.getTimeDifference()));
            newUser.setPuserid(parentUserID);
            newUser.setMobile(childUser.getMobile());
            newUser.setPassword(QEncodeUtil.md5Encrypt(childUser.getPassword()));
            newUser.setRemark(childUser.getRemark());
            newUser.setProperty(childUser.getProperty());
            newUser.setState(childUser.getState());
            newUser.setCreatetime(new Date());
            // 新增子用户
            if (sysUserService.insertSelective(newUser) > 0) {
                //* 子用户分配角色
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setAdminid(parentUserID);
                sysUserRole.setUpdatetime(new Date());
                sysUserRole.setCreatetime(new Date());
                sysUserRole.setRoleid(childUser.getRole());
                sysUserRole.setUserid(newUser.getUserid());
                if (sysUserRoleService.insertSelective(sysUserRole) > 0)
                    return WebResult.success().toMap();
                else
                    return WebResult.failure("新增的系统用户分配角色失败").toMap();
            } else
                return WebResult.failure("增加系统用户失败").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: changeChildUserPassowrd(final Long userid, final String password)
     * @Description: TODO(修改系统用户密码)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "changesystemuserpass", method = RequestMethod.POST)
    public Map<String, Object> changeSystemUserPassowrd(final Long userid, final String password) {
        try {
            SysUser newUser = new SysUser();
            newUser.setUserid(userid);
            newUser.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            newUser.setUpdatetime(new Date());
            newUser.setPassword(QEncodeUtil.md5Encrypt(password));
            if (sysUserService.updateByPrimaryKeySelective(newUser) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("修改密码失败，请与管理员联系").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: recoverPassowrd(final Long userid)
     * @Description: TODO(重置系统用户密码)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "recoversystemuserpassword", method = RequestMethod.POST)
    public Map<String, Object> recoverSystemUserPassowrd(final Long userid) {
        try {
            SysUser newUser = new SysUser();
            newUser.setUserid(userid);
            newUser.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            newUser.setUpdatetime(new Date());
            newUser.setPassword(QEncodeUtil.md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD));
            if (sysUserService.updateByPrimaryKeySelective(newUser) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("恢复密码失败，请与管理员联系").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: revomeChildUser(final Long userid)
     * @Description: TODO(删除系统用户)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "removesystemser", method = RequestMethod.POST)
    public Map<String, Object> revomeSystemUser(final Long userid) {
        try {
            //移除子账户的角色
            SysUserRoleCriteria criteria = new SysUserRoleCriteria();
            criteria.or().andUseridEqualTo(userid);
            sysUserRoleService.deleteByCriteria(criteria);
            //删除子账户信息
            if (sysUserService.deleteByPrimaryKey(userid) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("删除子账户失败，请与管理员联系").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: getRoles
     * @Description: TODO(获取角色权限)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "getrolemodules", method = RequestMethod.POST)
    public Map<String, Object> getRoleModules(final Long usergroupid) {
        try {

            return sysModuleService.getRoleModules(usergroupid);

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: getUserPlaces
     * @Description: TODO(设置角色权限)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "setuprolemodules", method = RequestMethod.POST)
    public Map<String, Object> setRoleModule(Long roleid, Long[] modules) {
        try {
            if (roleid == null || roleid.equals(0)) {
                return WebResult.failure("角色为空,非法操作").toMap();
            } else if (modules == null || modules.length <= 0) {
                return WebResult.failure("权限为空,非法操作").toMap();
            } else {
                /* 设置角色的权限之前，先清空掉原来已经设置好的权限 */
                Long adminid = privilegeService.getCurrentPrincipal().getUserid();
                SysRoleModuleCriteria criteria = new SysRoleModuleCriteria();
                criteria.or().andRoleidEqualTo(roleid).andAdminidEqualTo(adminid);
                sysRoleModuleService.deleteByCriteria(criteria);

                List<SysRoleModule> sysRoleModules = new ArrayList<SysRoleModule>();
                Date updatetime = new Date();
                for (Long module : modules) {
                    SysRoleModule rm = new SysRoleModule();
                    rm.setRoleid(roleid);
                    rm.setModuleid(module);
                    rm.setAdminid(adminid);
                    rm.setUpdatetime(updatetime);
                    sysRoleModules.add(rm);
                }

                if (sysRoleModuleService.setupRoleModule(sysRoleModules) > 0) {
                    return WebResult.success().toMap();
                } else {
                    return WebResult.failure("角色授权失败,请与管理员联系").toMap();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

}
